<?php
class BonusTransferCashPage extends MemberPage {
	private static $singular_name = "E-Bonus Transfer E-Cash Page";
    private static $plural_name = "E-Bonus Transfer E-Cash Pages";
    private static $default_parent = 'AccountTransferPage';

    private static $db = array();

    private static $has_one = array();

}

class BonusTransferCashPage_Controller extends MemberPage_Controller {

    /**
     * An array of actions that can be accessed via a request. Each array element
     * should be an action name, and the
     * permissions or conditions required to allow the user to access it.
     *
     * <code>
     * array (
     *     'action', // anyone can access this action
     *     'action' => true, // same as above
     *     'action' => 'ADMIN', // you must have ADMIN permissions to access this
     * action
     *     'action' => '->checkAction' // you can only access this action if
     * $this->checkAction() returns true
     * );
     * </code>
     *
     * @var array
     */
    private static $allowed_actions = array(
        'Form'
    );
	
	function init(){
		parent::init();
		$confirm_msg = _t('BonusTransferCashPage.CONFIRM_MSG', 'Are you sure you want to proceed transfer?');
		$js = <<<JS
			(function($) {
				$('form').submit(function(){
  					if (confirm("$confirm_msg")){
         				return true;
      				}
      				return false;
				});
			})(jQuery);
JS;
		Requirements::customScript($js, 'ConfirmTransfer');
	}

    function Form() {
    	$fields = singleton('BonusAccountTransferCashAccount')->getTransferFormFields($this->CurrentMember()->ID);
		
		$actions = FieldList::create(
            FormAction::create("doProceed", _t('BonusTransferCashPage.BUTTONPROCEEDTRANSFER', 'Proceed Transfer'))
        );
		
		$validator = RequiredFields::create('Transfer', 'Amount');
		
        return Form::create($this, 'Form', $fields, $actions, $validator);
    }
	
	function doProceed($data, $form) {
        try {
        	DB::getConn()->transactionStart();
        	$transfer_id = BonusAccountTransferCashAccount::create_statement($data, $this->CurrentMember()->ID, Distributor::get_id_by_username($data['Transfer']['username']));
            DB::getConn()->transactionEnd();
            return $this->redirect($this->BonusTransferCashStatementLink);
        }
        catch(ValidationException $e) {
            DB::getConn()->transactionRollback();
            SS_Log::log(new Exception(print_r($e->getMessage(), true)), SS_Log::NOTICE);
            $form->sessionMessage($e->getMessage(), 'bad');
        }
        return $this->redirectBack();
    }
}